<template>
  <el-dialog
    v-model="dialogVisible"
    title="新增/修改"
    width="720px"
    :before-close="handleClose"
    append-to-body
    destroy-on-close
  >
    <el-form
      label-position="right"
      label-width="80px"
      :model="formModel"
      ref="formInsRef"
      :rules="rules"
    >
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="用户名" prop="name">
            <el-input v-model="formModel.name" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="mobile">
            <el-input
              v-model="formModel.mobile"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!formModel?.id">
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="formModel.password"
              type="password"
              autocomplete="off"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!formModel?.id">
          <el-form-item label="确认密码" prop="checkPassword">
            <el-input
              v-model="formModel.checkPassword"
              type="password"
              autocomplete="off"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="formModel.email"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input v-model="formModel.age" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="role">
            <CommonSelect multiple :formatResult="formatResult" :apiFn="roleApi" v-model="formModel.role"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="formModel.sex">
              <el-radio-button
                :value="item.value"
                :key="item.value"
                v-for="item in enumnsToOptions(SEX_OBJ_ENUMS)"
              >
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="js" setup>
import { enumnsToOptions, setModel, omit } from "@/utils"
import { ref, reactive } from "vue"
import { SEX_OBJ_ENUMS } from "../const"
import { userUpsertApi, userAddApi } from "@/api/user"
import { roleApi } from "@/api/role"
import { ElMessage } from "element-plus"
import { encryption } from "@/utils/crypto"

const emits = defineEmits(["success"])
const dialogVisible = ref(false)
const formInsRef = ref()
const formModel = ref({
  id: "",
  name: "",
  mobile: "",
  password: "",
  checkPassword: "",
  email: "",
  age: "",
  role: "",
  sex: "",
})
const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入"))
  } else {
    if (formInsRef.value) {
      formInsRef.value.validateField("checkPassword")
    }
    callback()
  }
}
const checkPassword = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入"))
  } else if (value !== formModel.value.password) {
    callback(new Error("两次密码不一致"))
  } else {
    callback()
  }
}
const rules = reactive({
  name: [{ required: true, message: "请输入" }],
  mobile: [{ required: true, message: "请输入" }],
  password: [{ required: true, validator: validatePass }],
  checkPassword: [{ required: true, validator: checkPassword }],
  email: [{ required: true, message: "请输入" }],
})

const handleClose = () => {
  // done?.()
  formInsRef.value?.resetFields()
  dialogVisible.value = false
}

const open = ({ row } = {}) => {
  // Object.assign(formModel, setModel(formModel, row))
  formModel.value = { ...row, role: row?.role?.map(item => item.id) || undefined }
  dialogVisible.value = true
}

const buildParams = (params = {}) => {
  const postParams = {
    ...params,
    ...formModel.value,
    password: encryption(formModel.value.password),
    checkPassword: encryption(formModel.value.checkPassword),
  }
  return postParams
}

const formatResult = (item) => {
  return {
    // id: item?.id,
    value: item?.id,
    label: item?.label,
    // value: item?.value,
  }
}

const submitHandler = async () => {
  const params = buildParams();
  if (params?.id) {
    await userUpsertApi(omit(params, ['password', 'checkPassword']))
  } else {
    await userAddApi(omit(params, ['id']))
  }
  ElMessage.success("操作成功")
  emits("success")
}

const onClose = () => {
}

const onSubmit = () => {
  if (!formInsRef.value) return
  formInsRef.value.validate(async valid => {
    if (valid) {
      console.log("submit!")
      await submitHandler()
      handleClose()
      emits("success")
    } else {
      console.log("error submit!")
    }
  })
}

defineExpose({
  open,
})
</script>
